package com.yeeKa.common.exception;

import com.yeeKa.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@Slf4j
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result<Void> customizeExceptionHandler(MyException e){
        log.error(e.toString());
        return new Result<Void>().failure(e.getMessage());
    }

    @ExceptionHandler(My403Exception.class)
    @ResponseBody
    public Result<Void> My403ExceptionHandler(My403Exception e){
        Result<Void> result = new Result<>();
        result.setMsg(e.toString());
        result.setCode("403");
        return result;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result<String> handlerException(Exception e) {
        Result<String> result = new Result<>();
        log.error("服务器异常",e);
        result.failure("服务器异常"+e.getMessage());
        return result;
    }


    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result<String> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuffer buffer = new StringBuffer();

        BindingResult result  = e.getBindingResult();
        if (result.hasErrors()) {

            List<ObjectError> errors = result.getAllErrors();

            errors.forEach(p ->{

                FieldError fieldError = (FieldError) p;
                buffer.append(fieldError.getDefaultMessage()).append(",");
            });
        }
        Result<String> result1 = new Result<>();
        result1.failure("参数错误："+buffer.toString().substring(0, buffer.toString().length()-1));
        return result1;
    }
}